package com.wandian.texas.command.texas;

import com.wandian.texas.BaseCommandObject;
import com.wandian.texas.GamePool;
import com.wandian.texas.RoomMgr;
import com.wandian.texas.UserMgr;
import com.wandian.command.Cmd;
import com.wandian.command.UserCommand;
import com.wandian.texas.entity.UserInfoEntity;
import com.wandian.texas.protocol.Protocol;
import com.wandian.util.Log;
import com.wandian.xml.RoomConfigItem;

@Cmd(code = Protocol.EnterRoomCmd, desc = "")
public class EnterRoomCmd extends UserCommand {

	@Override
	public void execute(BaseCommandObject cmdObject) {
		super.execute(cmdObject);
		int type = cmdObject.readByte();
		UserInfoEntity user = cmdObject.getUser();
		switch (type) {
		case 0:// 3000 通知刚进入
				// 先做业务处理,
			int roomid = cmdObject.readInt();
//			Log.debug(user + " 进房间" + roomid);
			if (RoomMgr.inGame(cmdObject.sessionObject, roomid)) {
//				Log.debug("[EnterRoomCmd.Register]");
				cmdObject.setCmd(Protocol.CMD_REGISTER);
				sendEnterRoom(cmdObject, (byte) 1);// Setp 1:告诉请求接受
				// Command.CMD_PLAYERS:
				cmdObject.setCmd(Protocol.CMD_PLAYERS);
				sendRoomAllPlayer(cmdObject, roomid);// Step 2:先将房间数据发送
				// 当前坐位玩家
				cmdObject.setCmd(Protocol.RoomInfoCmd);
				sendCurrentSeatPlayer(cmdObject, roomid);// Step
															// 3,发坐位上数据，需要step2的详细数据
				cmdObject.setCmd(Protocol.InGAameRoomCmd);
				sendInGameRoom(cmdObject); // Step 4:广播通知其他人
			} else {
				sendEnterRoom(cmdObject, (byte) 0);// Setp 1:告诉请求接受
			}

			break;
		case 1:// 3001 房间当前状态信息,Response
			break;
		case 2:// 3002 房间当前状态信息,Response
				// 第一个入房间,等待，若有两个人就开始游戏
			user = cmdObject.getUser();
			if (user.seatId > 0)
				return;
			if (broadcastSitdown(cmdObject)) { // Step 1 :坐下,
				if (GamePool.broadcastStartGame(cmdObject, cmdObject.getUser().roomId)) {
					// Step 3:若前面条件成立,开始操牌
					GamePool.operationNext(cmdObject.getUser().roomId, cmdObject);
				}
//				Log.debug(String.format("[EnterRoomCmd.SitdownCmd]玩家%s坐下成功,房间:%s,坐位:%s", user.nickName, user.roomId, user.seatId));
			} else {
//				Log.debug(String.format("[EnterRoomCmd.SitdownCmd]玩家%s坐下失败,房间:%s,坐位:%s", user.nickName, user.roomId, user.seatId));
			}
			break;
		case 3:// 退出房间
			RoomMgr.outGame(cmdObject.sessionObject, cmdObject.dbIndex, cmdObject);
			// outGameRoom(cmdObject);
			break;
		case 4:// fast enter room FastEnterRoomCmd
			sendEmptyRoom(cmdObject);
			break;
		case 5://
			cmdObject.setCmd(Protocol.StandUpCmd);
			sendStandup(cmdObject);
			break;
		default:
			break;
		}

	}

	private void sendRoomAllPlayer(BaseCommandObject cmdObject, int roomid) {
		// 房间所有玩家列表
		RoomConfigItem room = RoomMgr.roomsMap.get(roomid);
		room.RoomDoorLock().lock();
		try {
			UserInfoEntity user;
			cmdObject.writeBegin();
			int roomUserCount = room.roomUserSize();
			cmdObject.writeInt(roomUserCount);
			for (int i = 0; i < roomUserCount; i++) {
				user = room.getRoomUser(i);
				cmdObject.writeInt(user.seatId);
//				Log.debug("发送房间列表:" + user);
				cmdObject.writeInt(user.userId);
				cmdObject.writeByte(user.sex);
				cmdObject.writeString(user.nickName);
				cmdObject.writeString(user.icon);
//				cmdObject.writeInt(user.vip);
//				cmdObject.writeInt(user.gold);
				cmdObject.writeFloat(user.money);
//				cmdObject.writeInt(user.sumGame);
//				cmdObject.writeInt(user.winGame);
//				cmdObject.writeInt(user.rank);
//				cmdObject.writeInt(user.winrank);
//				cmdObject.writeInt(user.giftPcate);
//				cmdObject.writeInt(user.giftPframe);
//				cmdObject.writeInt(user.banSpeak);
//				cmdObject.writeInt(user.yellowvip);
//				cmdObject.writeInt(user.isyearvip);
			}
			cmdObject.writeEnd();
			UserMgr.I().SendData(cmdObject);
		} finally {
			room.RoomDoorLock().unlock();
		}
	}

	private void sendStandup(BaseCommandObject cmdObject) {
		RoomMgr.sendStandup(cmdObject.sessionObject, cmdObject.dbIndex, cmdObject, false);
	}

	private void sendEmptyRoom(BaseCommandObject cmdObject) {
		// 广播该玩家信息到当前房间的所有用户
		UserInfoEntity user = cmdObject.getUser();
		// int money = cmdObject.readInt();
		if (user != null) {
			cmdObject.writeBegin();
			cmdObject.writeByte((byte) 1);// 1标志位成功，0 失败
			cmdObject.writeInt(RoomMgr.getFastEnterRoom());// roomid,应该每次加入房间，判断房间满人否，坐下也要判断
			cmdObject.writeEnd();
			cmdObject.setCmd(Protocol.FastEnterRoomCmd);
			UserMgr.I().SendData(cmdObject);
		} else {
			Log.error("不合法用户操作");
		}
	}

	/*private void outGameRoom(SessionObject session, BaseCommandObject cmdObject) {
		// 广播该玩家信息到当前房间的所有用户
		UserInfoEntity user = session.getUser();
		if (user != null && user.roomId > 0) {
			// 当前房间玩家都通知
			cmdObject.writeBegin();
			cmdObject.writeByte((byte) 1);// 1标志位成功，0 失败
			cmdObject.writeInt(user.userId);
			cmdObject.writeEnd();
			cmdObject.setCmd(Protocol.OutGameRoomCmd);
			UserMgr.I().broadCastToRoomUsers(cmdObject);
			// UserMgr.I().SendData(cmdObject);
			RoomMgr.outGame(session, cmdObject.dbIndex, cmdObject);
		} else {
			Log.error("不合法用户操作");
		}
	}*/

	/**
	 * 发给房间其他人
	 * 
	 * @param cmdObject
	 */
	private void sendInGameRoom(BaseCommandObject cmdObject) {
		// 广播该玩家信息到当前房间的所有用户
		UserInfoEntity user = cmdObject.getUser();
		if (user != null && user.roomId > 0) {
			// 当前房间玩家都通知
			cmdObject.writeBegin();
			cmdObject.writeByte((byte) 1);// 1标志位成功，0 失败
			cmdObject.writeInt(user.userId);
//			cmdObject.writeInt(user.personId);
			cmdObject.writeByte(user.sex);
			cmdObject.writeString(user.nickName);
//			Log.debug("玩家进入游戏,坐位形象ico:" + user.icon);
			cmdObject.writeString(user.icon);
//			cmdObject.writeInt(user.vip);
//			cmdObject.writeInt(user.gold);
			cmdObject.writeFloat(user.money);
//			cmdObject.writeInt(user.sumGame);
//			cmdObject.writeInt(user.winGame);
//			cmdObject.writeInt(user.rank);
//			cmdObject.writeInt(user.winrank);
//			cmdObject.writeInt(user.giftPcate);
//			cmdObject.writeInt(user.giftPframe);
//			cmdObject.writeInt(user.banSpeak);
//			cmdObject.writeInt(user.yellowvip);
//			cmdObject.writeInt(user.isyearvip);
			cmdObject.writeEnd();
			// cmdObject.setCmd(Protocol.InGAameRoomCmd);
			UserMgr.I().broadCastToRoomOtherUsers(cmdObject);
		} else {
			Log.error("不合法用户操作");
		}
	}

	/**
	 * 广播通知用户，房间有人坐下
	 * 
	 * @param cmdObject
	 * @return
	 */
	private boolean broadcastSitdown(BaseCommandObject cmdObject) {
		UserInfoEntity user = cmdObject.getUser();
		int seatId = cmdObject.readInt();
		float stake = cmdObject.readFloat();
		if (user != null && user.roomId > 0) {
			if (RoomMgr.sitdownGame(cmdObject.sessionObject, user.roomId, seatId, stake, cmdObject.dbIndex, cmdObject)) {
				if (user == null || user.stake <= 0) {
					throw new IllegalArgumentException("broadcastSitdown,sit succ,but stake 0 error" + user);
				}
				// 当前房间玩家都通知
				cmdObject.setCmd(Protocol.SitdownCmd);
				cmdObject.writeBegin();
				cmdObject.writeByte((byte) 1);// 1标志位成功，0 失败
				cmdObject.writeInt(user.userId);
				cmdObject.writeInt(user.seatId);
				cmdObject.writeFloat(user.stake);
				cmdObject.writeFloat(user.money);
				// cmdObject.writeInt(user.callChip);
				cmdObject.writeEnd();
				UserMgr.I().broadCastToRoomUsers(cmdObject);
				return true;
			} else {
				if (user.stake > 0) {
					throw new IllegalArgumentException("broadcastSitdown,sit error,but stake> 0 error" + user);
				}
				cmdObject.setCmd(Protocol.SitdownCmd);
				cmdObject.writeBegin();
				cmdObject.writeByte((byte) 0);// 1标志位成功，0 失败
				cmdObject.writeEnd();
				UserMgr.I().SendData(cmdObject);
			}
		} else {
			cmdObject.setCmd(Protocol.SitdownCmd);
			cmdObject.writeBegin();
			cmdObject.writeByte((byte) 0);// 1标志位成功，0 失败
			cmdObject.writeEnd();
			UserMgr.I().SendData(cmdObject);
			Log.error("不合法用户操作");
		}
		return false;
	}

	/**
	 * 将房间内坐位上玩家列表信息发送过去
	 * 
	 * @param cmdObject
	 */
	private void sendCurrentSeatPlayer(BaseCommandObject cmdObject, int roomid) {
		RoomConfigItem room = RoomMgr.roomsMap.get(roomid);
		cmdObject.writeBegin();
		if (room != null) {
			cmdObject.writeByte((byte) 1);
			cmdObject.writeInt(room.dealer());
			cmdObject.writeInt(room.seat);
			cmdObject.writeByte((byte) room.bettime);

			// 公共牌
			cmdObject.writeInt(room.currPublicCardLen());
//			Log.debug("玩家进入，发布当然的底牌过去！下面是底牌！");
			for (int i = 0; i < room.currPublicCardLen(); i++) {
				cmdObject.writeString(room.PublicCards(i));
//				Log.debug(room.PublicCards(i));
			}
			if (!room.isPlaying()) {
				cmdObject.writeInt(0);
			} else {
				cmdObject.writeInt(room.BonusPoolsSize());

				// 边池
				for (int i = 0; i < room.BonusPoolsSize(); i++) {
					cmdObject.writeFloat(room.bonusPool(i));
				}
			}

			cmdObject.writeInt(room.isPlaying() ? 1 : 0);
			cmdObject.writeInt(room.curSeatId());
			cmdObject.writeInt(room.curTime());
			// 坐位上的玩家[seatwait+seatuser]
			int seatUserCount = room.roomSeatSize();
			cmdObject.writeInt(seatUserCount);
			UserInfoEntity user;
			// 只遍历seatuser会index超出
			for (int i = 1; i <= 9; i++) {
				user = room.getUser(i);
				if (user == null || user.seatId < 1)
					continue;
				cmdObject.writeInt(user.seatId);
				cmdObject.writeInt(user.userId);
				cmdObject.writeInt(user.state);
				cmdObject.writeInt(user.lastAction);
				cmdObject.writeFloat(room.callChip(user.seatId));
				cmdObject.writeFloat(user.stake);
			}
//			Log.debug("[EnterRoomCmd]发送房间人员信息,将房间内座位上玩家列表:" + seatUserCount);
		} else {
			cmdObject.writeByte((byte) 0);
//			Log.debug("[EnterRoomCmd]发送房间,房间不存在");
		}
		cmdObject.writeEnd();
		// cmdObject.setCmd(Protocol.RoomInfoCmd);
		UserMgr.I().SendData(cmdObject);
	}

	/**
	 * 通知客户端,进入请求已接收
	 * 
	 * @param cmdObject
	 */
	private void sendEnterRoom(BaseCommandObject cmdObject, byte result) {
		// 先做业务处理,
		cmdObject.writeBegin();
		cmdObject.writeByte(result);//
		cmdObject.writeEnd();
		UserMgr.I().SendData(cmdObject);
//		Log.debug("[EnterRoomCmd]通知客户端,进入请求已接收");
	}
}
